package services

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
)

// OCRService OCR 服务
type OCRService struct {
	apiURL    string
	apiKey    string
	apiSecret string
}

// NewOCRService 创建 OCR 服务
func NewOCRService() *OCRService {
	return &OCRService{
		apiURL:    getEnv("OCR_API_URL", ""),
		apiKey:    getEnv("OCR_API_KEY", ""),
		apiSecret: getEnv("OCR_API_SECRET", ""),
	}
}

// OCRResult OCR 识别结果
type OCRResult struct {
	Success bool                   `json:"success"`
	Data    map[string]interface{} `json:"data"`
	Message string                 `json:"message"`
}

// RecognizeImage 识别图片
func (s *OCRService) RecognizeImage(imagePath string) (*OCRResult, error) {
	// 读取图片文件
	file, err := os.Open(imagePath)
	if err != nil {
		return &OCRResult{
			Success: false,
			Message: fmt.Sprintf("打开图片失败: %v", err),
		}, err
	}
	defer file.Close()

	// 读取图片文件数据
	fileData, err := io.ReadAll(file)
	if err != nil {
		return &OCRResult{
			Success: false,
			Message: fmt.Sprintf("读取图片失败: %v", err),
		}, err
	}

	// 调用 OCR API（这里需要根据实际的 OCR 服务商 API 进行调整）
	if s.apiURL == "" {
		// 如果没有配置 API，返回模拟数据
		return s.mockOCRResult(), nil
	}

	// 实际 API 调用
	req, err := http.NewRequest("POST", s.apiURL, bytes.NewReader(fileData))
	if err != nil {
		return &OCRResult{
			Success: false,
			Message: fmt.Sprintf("创建请求失败: %v", err),
		}, err
	}

	req.Header.Set("Content-Type", "application/octet-stream")
	if s.apiKey != "" {
		req.Header.Set("Authorization", "Bearer "+s.apiKey)
	}

	client := &http.Client{Timeout: 30 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		return &OCRResult{
			Success: false,
			Message: fmt.Sprintf("API 调用失败: %v", err),
		}, err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return &OCRResult{
			Success: false,
			Message: fmt.Sprintf("读取响应失败: %v", err),
		}, err
	}

	var result OCRResult
	err = json.Unmarshal(body, &result)
	if err != nil {
		return &OCRResult{
			Success: false,
			Message: fmt.Sprintf("解析响应失败: %v", err),
		}, err
	}

	return &result, nil
}

// mockOCRResult 模拟 OCR 结果（用于测试）
func (s *OCRService) mockOCRResult() *OCRResult {
	return &OCRResult{
		Success: true,
		Data: map[string]interface{}{
			"姓名":     "张三",
			"身份证号":  "110101199001011234",
			"地址":     "北京市朝阳区xxx街道",
			"电话":     "13800138000",
			"日期":     time.Now().Format("2006-01-02"),
		},
		Message: "识别成功（模拟数据）",
	}
}

// SetAPIConfig 设置 API 配置
func (s *OCRService) SetAPIConfig(url, key, secret string) {
	s.apiURL = url
	s.apiKey = key
	s.apiSecret = secret
}

func getEnv(key, defaultValue string) string {
	value := os.Getenv(key)
	if value == "" {
		return defaultValue
	}
	return value
}

